//
//  UITableView+Placeholder.m
//  UITableViewPlaceholder
//
//  Created by ZMC on 2018/10/5.
//  Copyright © 2018年 YaQi. All rights reserved.
//

#import "UITableView+Placeholder.h"
#import <objc/runtime.h>

@implementation UITableView (Placeholder)


//class_getInstanceMethod 得到类方法
//class_addMethod:如果发现方法已经存在，会失败返回，也可以用来做检查用
void swizzMethod(SEL oriSel, SEL newSel) {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        Class class = [UITableView class];
        Method oriMethod = class_getInstanceMethod(class, oriSel);
        Method newMethod = class_getInstanceMethod(class, newSel);
        
        BOOL success = class_addMethod(class, oriSel, method_getImplementation(newMethod), method_getTypeEncoding(newMethod));
        if (success) {
            class_replaceMethod(class, newSel, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
        } else {
            method_exchangeImplementations(oriMethod, newMethod);
        }
    });
    
    
}

+(void)load {
    //还可以加入很多对插入删除的,对数据有影响的方法
//    SEL selectors[]={
//        @selector(reloadData),
//    };
    SEL oriSelector = @selector(reloadData);
    SEL newSelector = NSSelectorFromString([@"mc_" stringByAppendingString:NSStringFromSelector(oriSelector)]);
    swizzMethod(oriSelector, newSelector);
}

- (void)mc_reloadData {
    [self mc_reloadData];
    [self showPlaceholder];
}

- (void)showPlaceholder {
//    if (self.showNoDataNotice) {
        NSInteger sectionCnt=self.numberOfSections;
        NSInteger rowCtn=0;
        for (int i=0; i<sectionCnt; i++) {
            rowCtn+=[self.dataSource tableView:self numberOfRowsInSection:i];
        }
        //没有任何数据
        if (rowCtn==0) {
            if (self.placeholderView) {
                self.backgroundView=[self placeholderView];
            }
            else {
                self.backgroundView=[self mc_defaultNoDataView];
            }
        }
        else {
            self.backgroundView=[[UIView alloc] init];
        }
//    }
}


- (UIView*)mc_defaultNoDataView {
    if (self.placeholderView) {
        return self.placeholderView;
    }
    else {
        UIView*view=[[UIView alloc] initWithFrame:self.bounds];
        UITapGestureRecognizer*tapGes=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapViewAction:)];
        [view addGestureRecognizer:tapGes];
        [view addSubview:self.defaultImageView];
        [view addSubview:self.dafaultLabel];
        [self layoutDefaultView];
        self.defaultNoDataView=view;
        return self.defaultNoDataView;
        
    }
}

- (void)tapViewAction:(UITapGestureRecognizer*)tap {
    
    self.defaultNoDataViewDidClickBlock ? self.defaultNoDataViewDidClickBlock(self.defaultNoDataView) : nil;
}

-(UIImageView*)defaultImageView {
    UIImageView *imageView = objc_getAssociatedObject(self, _cmd);
    if (!imageView) {
        imageView = [[UIImageView alloc] init];
        imageView.image = self.placeholderImage ? : [UIImage imageNamed:@"UITableViewPlaceholder.bundle/TableViewNoData"];
        imageView.contentMode = UIViewContentModeCenter;
        objc_setAssociatedObject(self, _cmd, imageView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return imageView;
}

-(UILabel*)dafaultLabel {
    UILabel*label=objc_getAssociatedObject(self, _cmd);
    if (!label) {
        label = [[UILabel alloc] init];
        label.text = self.placeholderText ? : @"暂无数据,点击刷新";
        label.font = [UIFont systemFontOfSize:11];
        label.textAlignment = NSTextAlignmentCenter;
        objc_setAssociatedObject(self, _cmd, label, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return label;
}

- (void)layoutDefaultView {
    UIImageView *imageView = self.defaultImageView;
    UIImage *image = self.placeholderImage ? : [UIImage imageNamed:@"UITableViewPlaceholder.bundle/TableViewNoData"];
    imageView.image = image;
    CGFloat X = (self.bounds.size.width - image.size.width - self.contentInset.left - self.contentInset.right) / 2;
    CGFloat Y = (self.bounds.size.height - image.size.height - self.contentInset.top - self.contentInset.bottom) / 2 - 20;
    imageView.frame = CGRectMake(X, Y, image.size.width, image.size.height);
    
    // 提示语不用太长，不考虑换行的情况，也不计算文字的宽高了
    UILabel *label = self.dafaultLabel;
    label.text = self.placeholderText ? : label.text;
    label.frame = CGRectMake(15, imageView.frame.origin.y + imageView.bounds.size.height + 10, self.bounds.size.width-30, 30);
}

#pragma mark - 副属性

-(UIView*)defaultNoDataView {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setDefaultNoDataView:(UIView*)defaultNoDataView {
        objc_setAssociatedObject(self, @selector(defaultNoDataView), defaultNoDataView, OBJC_ASSOCIATION_ASSIGN);
}

-(BOOL)showNoDataNotice {
    //默认yes
    return objc_getAssociatedObject(self, _cmd) == nil ? YES : [objc_getAssociatedObject(self, _cmd) boolValue];
}

- (void)setShowNoDataNotice:(BOOL)showNoDataNotice {
    objc_setAssociatedObject(self, @selector(showNoDataNotice), @(showNoDataNotice), OBJC_ASSOCIATION_ASSIGN);
}


#pragma mark - runtime 新属性

- (void)setPlaceholderText:(NSString *)placeholderText {
    objc_setAssociatedObject(self, @selector(placeholderText), placeholderText, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

-(void)setPlaceholderView:(UIView *)placeholderView {
    objc_setAssociatedObject(self, @selector(placeholderView), placeholderView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(void)setPlaceholderImage:(UIImage *)placeholderImage {
        objc_setAssociatedObject(self, @selector(placeholderImage), placeholderImage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(void)setDefaultNoDataViewDidClickBlock:(void (^)(UIView * _Nonnull))defaultNoDataViewDidClickBlock {
    
            objc_setAssociatedObject(self, @selector(defaultNoDataViewDidClickBlock), defaultNoDataViewDidClickBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

-(NSString*)placeholderText {
    return objc_getAssociatedObject(self, _cmd);
}

-(UIView*)placeholderView {
     return objc_getAssociatedObject(self, _cmd);
}

-(UIImage*)placeholderImage {
     return objc_getAssociatedObject(self, _cmd);
}

- (void (^)(UIView *))defaultNoDataViewDidClickBlock {
    return objc_getAssociatedObject(self, _cmd);
}


@end
